package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.constants.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

public class CustomerAction extends BaseAction<Customer> {
	@Resource(name = "jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Action(value = "customer_sendSms")
	public String customerSendSms() {
		// 手机号保存到customer对象里
		// 生成短信代码
		String randomCode = RandomStringUtils.randomNumeric(4);
		// 将短信验证码 保存到session
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);

		System.out.println("生成手机验证码为：" + randomCode);
		// 编辑短信内容
		final String msg = "尊敬的用户您好，本次获取的验证码为：" + randomCode + ",服务电话：4006184000";
		// 调用MQ服务,发送一条消息
		jmsTemplate.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}
		});
		return NONE;
	}

	// 属性驱动获取验证码
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Resource
	private RedisTemplate<String, String> redisTemplate;

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String customerRegist() {
		// 将页面获取的验证码数据跟session中保存的验证码数据进行对比
		String checkcodeSession = (String) ServletActionContext.getRequest().getSession()
				.getAttribute(model.getTelephone());
		if (checkcodeSession == null || !checkcodeSession.equals(checkcode)) {
			System.out.println("短信验证码错误");
			return INPUT;
		} else {
			System.out.println("用户注册成功");
			WebClient.create("http://localhost:9010/crm_management/services/customerService/customer")
					.accept(MediaType.APPLICATION_JSON).post(model);
			// 发送一封邮件
			String activecode = RandomStringUtils.randomNumeric(32);
			// 将激活码redis,设置24小时失效
			redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
			// 调用MailUtil发送激活邮件
			String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='" + MailUtils.activeUrl + "?telephone="
					+ model.getTelephone() + "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
			// 发送邮件
			MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
			return SUCCESS;
		}
	}

	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value = "customer_activeMail")
	public String customerActiveMail() throws IOException {
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		// 判断激活吗是否有效
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		if (activecodeRedis == null || !activecodeRedis.equals(activecode)) {
			// 激活码无效
			ServletActionContext.getResponse().getWriter().println("激活码无效，请登录系统，重新绑定邮箱！");
		} else {
			// 激活码有效
			// 防止重复绑定
			// 调用CRM webService 查询客户信息，判断是否已经绑定
			Customer customer = WebClient.create("http://localhost:9010/crm_management/services"
					+ "/customerService/customer/telephone/" + model.getTelephone()).accept(MediaType.APPLICATION_JSON)
					.get(Customer.class);
			if (customer.getType() == null || customer.getType() != 1) {
				// 没有绑定,进行绑定
				WebClient.create("http://localhost:9010/crm_management/services/customerService/customer/updatetype/"
						+ model.getTelephone()).get();
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
			} else {
				// 已经绑定过
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过，无需重复绑定！");
			}
			// 删除redis的激活码
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}

	// 客户登录的方法
	@Action(value = "customer_login", results = { @Result(name = "success", type = "json") })
	public String login() {
		// 创建map结果集
		Map<String, Object> result = new HashMap<>();
		// 查询是否有当前的用户
		Customer customer = WebClient.create("http://localhost:9010/crm_management/services"
				+ "/customerService/customer/telephone/" + model.getTelephone()).accept(MediaType.APPLICATION_JSON)
				.get(Customer.class);
		if (customer == null) {
			// 用户不存在
			result.put("success", false);
			result.put("msg", "账户名不存在,请重新输入");
		} else {
			// 对比密码
			if (!customer.getPassword().equals(model.getPassword())) {
				result.put("success", false);
				result.put("msg", "账户名与密码不匹配,请重新输入!");
			} else {
				ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
				// 正确
				result.put("success", true);

			}
		}
		// 将结果集压入值栈
		ActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}
}
